package com.example.dw.admin.controller;

import com.example.dw.common.Result;
import com.example.dw.admin.entity.AdminUser;
import com.example.dw.admin.mapper.AdminUserMapper;
import com.example.dw.utils.PasswordUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管理端测试控制器
 * 仅用于开发和测试环境，生产环境应移除或禁用
 * @author system
 * @since 2024-01-01
 */
@Tag(name = "管理端测试", description = "管理员测试和初始化接口")
@Slf4j
@RestController
@RequestMapping("/admin/test")
public class AdminTestController {

    @Autowired
    private AdminUserMapper adminUserMapper;

    /**
     * 创建测试管理员账号
     */
    @Operation(summary = "创建测试管理员", description = "创建默认的测试管理员账号")
    @PostMapping("/init-admin")
    public Result<?> initTestAdmin() {
        try {
            // 检查是否已存在管理员
            QueryWrapper<AdminUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username", "admin");
            AdminUser existingAdmin = adminUserMapper.selectOne(queryWrapper);
            
            if (existingAdmin != null) {
                Map<String, Object> data = new HashMap<>();
                data.put("username", "admin");
                data.put("message", "管理员已存在");
                data.put("loginInfo", "用户名: admin, 密码: admin123");
                return Result.success("测试管理员已存在", data);
            }
            
            // 创建测试管理员
            AdminUser testAdmin = new AdminUser();
            testAdmin.setUsername("admin");
            testAdmin.setPassword(PasswordUtil.encode("admin123")); // 默认密码: admin123
            testAdmin.setNickname("超级管理员");
            testAdmin.setPhone("13888888888");
            testAdmin.setEmail("admin@test.com");
            testAdmin.setSex("1"); // 1-男性
            testAdmin.setCreatedAt(LocalDateTime.now().toString());
            
            int result = adminUserMapper.insert(testAdmin);
            
            if (result > 0) {
                Map<String, Object> data = new HashMap<>();
                data.put("id", testAdmin.getId());
                data.put("username", testAdmin.getUsername());
                data.put("nickname", testAdmin.getNickname());
                data.put("phone", testAdmin.getPhone());
                data.put("email", testAdmin.getEmail());
                data.put("loginInfo", "用户名: admin, 密码: admin123");
                
                log.info("测试管理员创建成功: {}", testAdmin.getUsername());
                return Result.success("测试管理员创建成功", data);
            } else {
                return Result.error("测试管理员创建失败");
            }
            
        } catch (Exception e) {
            log.error("创建测试管理员失败: {}", e.getMessage());
            return Result.error("创建测试管理员失败: " + e.getMessage());
        }
    }

    /**
     * 创建多个测试管理员
     */
    @Operation(summary = "批量创建测试管理员", description = "创建多个不同角色的测试管理员")
    @PostMapping("/init-multiple-admins")
    public Result<?> initMultipleTestAdmins() {
        try {
            // 定义要创建的管理员列表
            AdminUser[] testAdmins = {
                createTestAdmin("admin", "admin123", "超级管理员", "13888888888", "admin@test.com"),
                createTestAdmin("manager", "manager123", "运营管理员", "13999999999", "manager@test.com"),
                createTestAdmin("editor", "editor123", "内容编辑", "13777777777", "editor@test.com")
            };

            Map<String, Object> results = new HashMap<>();
            int successCount = 0;
            
            for (AdminUser admin : testAdmins) {
                try {
                    // 检查是否已存在
                    QueryWrapper<AdminUser> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("username", admin.getUsername());
                    AdminUser existing = adminUserMapper.selectOne(queryWrapper);
                    
                    if (existing == null) {
                        int result = adminUserMapper.insert(admin);
                        if (result > 0) {
                            successCount++;
                            results.put(admin.getUsername(), "创建成功 - 密码: " + admin.getUsername() + "123");
                        } else {
                            results.put(admin.getUsername(), "创建失败");
                        }
                    } else {
                        results.put(admin.getUsername(), "已存在 - 密码: " + admin.getUsername() + "123");
                    }
                } catch (Exception e) {
                    results.put(admin.getUsername(), "创建失败: " + e.getMessage());
                }
            }
            
            Map<String, Object> data = new HashMap<>();
            data.put("总数", testAdmins.length);
            data.put("新创建", successCount);
            data.put("详情", results);
            data.put("说明", "所有管理员的密码格式为: 用户名 + 123");
            
            return Result.success("批量创建测试管理员完成", data);
            
        } catch (Exception e) {
            log.error("批量创建测试管理员失败: {}", e.getMessage());
            return Result.error("批量创建测试管理员失败: " + e.getMessage());
        }
    }

    /**
     * 重置测试管理员密码
     */
    @Operation(summary = "重置管理员密码", description = "重置指定管理员密码为默认值")
    @PostMapping("/reset-password")
    public Result<?> resetPassword(@RequestParam String username) {
        try {
            QueryWrapper<AdminUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username", username);
            AdminUser admin = adminUserMapper.selectOne(queryWrapper);
            
            if (admin == null) {
                return Result.error("管理员不存在: " + username);
            }
            
            // 重置密码为: 用户名 + 123
            String defaultPassword = username + "123";
            AdminUser updateAdmin = new AdminUser();
            updateAdmin.setId(admin.getId());
            updateAdmin.setPassword(PasswordUtil.encode(defaultPassword));
            updateAdmin.setUpdatedAt(LocalDateTime.now());
            
            int result = adminUserMapper.updateById(updateAdmin);
            
            if (result > 0) {
                Map<String, Object> data = new HashMap<>();
                data.put("username", username);
                data.put("newPassword", defaultPassword);
                
                log.info("管理员密码重置成功: {}", username);
                return Result.success("密码重置成功", data);
            } else {
                return Result.error("密码重置失败");
            }
            
        } catch (Exception e) {
            log.error("重置管理员密码失败: {}", e.getMessage());
            return Result.error("重置管理员密码失败: " + e.getMessage());
        }
    }

    /**
     * 查看所有管理员列表
     */
    @Operation(summary = "查看管理员列表", description = "查看系统中所有管理员账号")
    @GetMapping("/list-admins")
    public Result<?> listAdmins() {
        try {
            List<AdminUser> adminList = adminUserMapper.selectList(null);
            
            Map<String, Object> data = new HashMap<>();
            data.put("总数", adminList.size());
            data.put("管理员列表", adminList.stream().map(admin -> {
                Map<String, Object> adminInfo = new HashMap<>();
                adminInfo.put("id", admin.getId());
                adminInfo.put("username", admin.getUsername());
                adminInfo.put("nickname", admin.getNickname());
                adminInfo.put("phone", admin.getPhone());
                adminInfo.put("email", admin.getEmail());
                adminInfo.put("sex", admin.getSex());
                adminInfo.put("createdAt", admin.getCreatedAt());
                return adminInfo;
            }).toList());
            
            return Result.success("获取管理员列表成功", data);
            
        } catch (Exception e) {
            log.error("获取管理员列表失败: {}", e.getMessage());
            return Result.error("获取管理员列表失败: " + e.getMessage());
        }
    }

    /**
     * 删除测试管理员
     */
    @Operation(summary = "删除测试管理员", description = "删除指定的测试管理员账号")
    @DeleteMapping("/delete-admin")
    public Result<?> deleteTestAdmin(@RequestParam String username) {
        try {
            QueryWrapper<AdminUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username", username);
            AdminUser admin = adminUserMapper.selectOne(queryWrapper);
            
            if (admin == null) {
                return Result.error("管理员不存在: " + username);
            }
            
            int result = adminUserMapper.deleteById(admin.getId());
            
            if (result > 0) {
                Map<String, Object> data = new HashMap<>();
                data.put("deletedUsername", username);
                data.put("deletedId", admin.getId());
                
                log.info("测试管理员删除成功: {}", username);
                return Result.success("管理员删除成功", data);
            } else {
                return Result.error("管理员删除失败");
            }
            
        } catch (Exception e) {
            log.error("删除测试管理员失败: {}", e.getMessage());
            return Result.error("删除测试管理员失败: " + e.getMessage());
        }
    }

    /**
     * 创建测试管理员对象的辅助方法
     */
    private AdminUser createTestAdmin(String username, String password, String nickname, String phone, String email) {
        AdminUser admin = new AdminUser();
        admin.setUsername(username);
        admin.setPassword(PasswordUtil.encode(password));
        admin.setNickname(nickname);
        admin.setPhone(phone);
        admin.setEmail(email);
        admin.setSex("1"); // 默认男性
        admin.setCreatedAt(LocalDateTime.now().toString());
        return admin;
    }
} 